const express = require('express');
const router = express.Router();
const drugController = require('../controllers/drugController');
const pool = require('../database/pool');

// 获取所有药品
router.get('/', drugController.getAllDrugs);

// 创建新药品
router.post('/', drugController.createDrug);

// 根据 ID 获取药品
router.get('/:id', drugController.getDrugById);

// 更新药品信息
router.put('/:id', drugController.updateDrug);

// 更新药品库存
router.put('/:id/stock', async (req, res) => {
  try {
    const { id } = req.params;
    const { quantity } = req.body;

    // 获取当前库存
    const [drugs] = await pool.execute(
      'SELECT stock FROM drugs WHERE id = ?',
      [id]
    );

    if (drugs.length === 0) {
      return res.status(404).json({ message: '药品不存在' });
    }

    const currentStock = drugs[0].stock;
    const newStock = currentStock - quantity;

    if (newStock < 0) {
      return res.status(400).json({ message: '库存不足' });
    }

    // 更新库存
    await pool.execute(
      'UPDATE drugs SET stock = ? WHERE id = ?',
      [newStock, id]
    );

    res.json({ message: '库存更新成功' });
  } catch (error) {
    console.error('更新库存错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除药品
router.delete('/:id', drugController.deleteDrug);

module.exports = router; 